import { App } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import { RouteName } from "@/constant/route";
import NProgress from "nprogress";
import useUserStore from "@/store/user";

export default function installRouter(app: App) {
  const userStore = useUserStore();
  const router = createRouter({
    history: createWebHistory(),
    routes: [
      {
        name: "root",
        path: "/",
        component: () => import("@/components/GuatLayout/index.vue"),
        redirect: { name: RouteName.CONSOLE },
        children: [
          {
            name: RouteName.CONSOLE,
            path: "console",
            component: () => import("@/views/console/index.vue"),
            meta: {
              label: "控制台",
              icon: "ph:squares-four",
            },
          },
          {
            name: RouteName.NOT_FOUND,
            path: ":pathMatch(.*)",
            component: () => import("@/views/not-found/index.vue"),
            meta: {
              isShow: false,
            },
          },
        ],
      },
      {
        name: RouteName.LOGIN,
        path: "/login",
        component: () => import("@/views/login/index.vue"),
      },
    ],
  });

  watch(
    () => userStore.authRoutes,
    () => {
      userStore.getAuthRoutes.forEach((route) => router.addRoute(RouteName.ROOT, route));
    },
    { immediate: true }
  );
  router.beforeEach((_to, _, next) => {
    NProgress.start();
    next();
  });

  router.afterEach(() => {
    NProgress.done(true);
  });

  app.use(router);
}
